package cn.nfwx.tv.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseDialogFragment;

/**
 * Created by zhouzechao on 2017/11/24.
 */

public class LoadingDialogFragment extends BaseDialogFragment {
    private final static String BUNDLE_NAME_MESSAGE = "message";
    private final static String BUNDLE_NAME_CANCELABLE = "cancelable";
    private ImageView mImgView;
    private Animation operatingAnim;

    public static LoadingDialogFragment newInstance(String message, boolean cancelable) {
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_NAME_MESSAGE, message);
        bundle.putBoolean(BUNDLE_NAME_CANCELABLE, cancelable);
        LoadingDialogFragment fragment = new LoadingDialogFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected boolean isOutsideTouchable() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_loading;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        boolean cancelable = false;
        if (bundle != null) {
            cancelable = bundle.getBoolean(BUNDLE_NAME_CANCELABLE);
        }
        if (!cancelable) {
            setCancelable(false);
        }
        String message = null;
        if (bundle != null) {
            message = bundle.getString(BUNDLE_NAME_MESSAGE);
        }
        mImgView = findView(R.id.dialog_loading_img);
        TextView textView = findView(R.id.dialog_loading_tv_message);
        if (!TextUtils.isEmpty(message)) {
            textView.setText(message);
            textView.setVisibility(View.VISIBLE);
        } else {
            textView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_anim);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        mImgView.setAnimation(operatingAnim);
        mImgView.startAnimation(operatingAnim);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mImgView.clearAnimation();
        if (operatingAnim != null) {
            operatingAnim.cancel();
            operatingAnim = null;
        }
    }
}
